package com.franklin.java.completion.map;

import com.franklin.java.api.psi.data.PsiCallingElement;
import com.franklin.java.utils.CompletionUtils;
import com.franklin.java.utils.PsiUtils;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * Map数据输入处理器
 * @author Franklin
 * @since 2021/09/04 18:20
 */
class MapDataInsertHandler implements InsertHandler<LookupElement> {

    private MapData mapData;

    private PsiCallingElement psiCallingElement;

    private final static String fillExpressionBase = "(%s)%s.get(%s)";

    MapDataInsertHandler(MapData mapData, PsiCallingElement psiCallingElement) {
        this.mapData = mapData;
        this.psiCallingElement = psiCallingElement;
    }

    @Override
    public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) {
        String key = mapData.getKey().getValue();
        String type = mapData.getValue().getType();
        PsiElement callingElement = psiCallingElement.getCallingElement();
        int startOffset = psiCallingElement.getStartOffsetInPsiFile();
        String input = String.format(fillExpressionBase, type, callingElement.getText(), key);
        Document document = context.getDocument();
        document.replaceString(startOffset,context.getTailOffset(),input);
        context.commitDocument();
    }
}
